package com.tai.network;


import org.junit.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * The type Random access file demo.
 *
 * @author taylor
 * @Description: 既可以输入流 也可以是输出流
 * @date 2021 /6/23 20:17
 */
public class RandomAccessFileDemo {

    /**
     * Test 1.
     */
    @Test
    public void test1(){
        try (RandomAccessFile randomAccessFile1 = new RandomAccessFile(new File("temp/jvm.jpg"),"r");
             RandomAccessFile randomAccessFile2 = new RandomAccessFile(new File("temp/jvm_bak.jpg"),"rw")){

            byte[] buffer = new byte[1024];
            int len;
            while ((len=randomAccessFile1.read(buffer))!=-1){

                randomAccessFile2.write(buffer,0,len);
            }
        }  catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * Test 2.
     */
    @Test
    public void test2(){
        try (RandomAccessFile randomAccessFile1 = new RandomAccessFile(new File("temp/test.txt"),"rw")
        ){
            randomAccessFile1.seek(randomAccessFile1.length());
            randomAccessFile1.write("llllllll".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
